// 智能预警引擎模块 - 负责告警规则处理、触发和管理

class AlertEngine {
    constructor() {
        this.rules = [];
        this.alerts = [];
        this.maxAlerts = 1000;
        this.alertCounters = {
            total: 0,
            active: 0,
            resolved: 0,
            bySeverity: { critical: 0, high: 0, medium: 0, low: 0 }
        };
        this.listeners = {};
        this.isRunning = false;
    }

    // 初始化预警引擎
    init() {
        console.log('智能预警引擎初始化...');
        
        // 创建默认告警规则
        this.createDefaultRules();
        
        // 将告警引擎添加到数据引擎的监听器
        if (realTimeSystem.modules.dataStream) {
            realTimeSystem.modules.dataStream.on('realtime:updated', this.checkRules.bind(this));
            realTimeSystem.modules.dataStream.on('finance:updated', this.checkRules.bind(this));
            realTimeSystem.modules.dataStream.on('iot:updated', this.checkRules.bind(this));
            realTimeSystem.modules.dataStream.on('system:updated', this.checkRules.bind(this));
        }
        
        this.isRunning = true;
        console.log('智能预警引擎初始化完成');
    }

    // 创建默认告警规则
    createDefaultRules() {
        // 系统性能告警规则
        this.addRule({
            id: 'system_cpu_high',
            name: 'CPU使用率过高',
            description: '系统CPU使用率超过80%',
            dataSource: 'system',
            condition: 'value.cpu > 80',
            severity: 'high',
            notification: true,
            autoResolve: true,
            resolveCondition: 'value.cpu < 70',
            debounceTime: 30000 // 30秒去抖
        });

        this.addRule({
            id: 'system_memory_high',
            name: '内存使用率过高',
            description: '系统内存使用率超过85%',
            dataSource: 'system',
            condition: 'value.memory > 85',
            severity: 'medium',
            notification: true,
            autoResolve: true,
            resolveCondition: 'value.memory < 75'
        });

        // 金融数据告警规则
        this.addRule({
            id: 'finance_price_drop',
            name: '价格急剧下跌',
            description: '价格在短时间内下跌超过5%',
            dataSource: 'finance',
            condition: 'value.priceChangePercent < -5',
            severity: 'high',
            notification: true,
            category: '金融'
        });

        this.addRule({
            id: 'finance_volume_spike',
            name: '成交量突增',
            description: '成交量突增超过100%',
            dataSource: 'finance',
            condition: 'value.volumeChangePercent > 100',
            severity: 'medium',
            notification: true,
            category: '金融'
        });

        // IoT设备告警规则
        this.addRule({
            id: 'iot_device_offline',
            name: '设备离线',
            description: '物联网设备状态为离线',
            dataSource: 'iot',
            condition: 'value.status === "offline"',
            severity: 'critical',
            notification: true,
            category: '设备',
            autoResolve: true,
            resolveCondition: 'value.status === "online"'
        });

        this.addRule({
            id: 'iot_temperature_high',
            name: '设备温度过高',
            description: '设备温度超过预设阈值',
            dataSource: 'iot',
            condition: 'value.temperature > 80',
            severity: 'high',
            notification: true,
            category: '设备',
            autoResolve: true,
            resolveCondition: 'value.temperature < 70'
        });
    }

    // 添加告警规则
    addRule(ruleConfig) {
        const rule = {
            id: ruleConfig.id || `rule_${Date.now()}`,
            name: ruleConfig.name || '未命名规则',
            description: ruleConfig.description || '',
            dataSource: ruleConfig.dataSource,
            condition: ruleConfig.condition,
            severity: ruleConfig.severity || 'medium',
            notification: ruleConfig.notification !== false,
            category: ruleConfig.category || '默认',
            autoResolve: ruleConfig.autoResolve || false,
            resolveCondition: ruleConfig.resolveCondition,
            debounceTime: ruleConfig.debounceTime || 0,
            enabled: ruleConfig.enabled !== false,
            createdAt: Date.now(),
            lastTriggered: null,
            triggerCount: 0,
            _lastFired: 0 // 内部使用，用于去抖
        };

        this.rules.push(rule);
        console.log(`告警规则已添加: ${rule.name} (${rule.id})`);
        
        return rule;
    }

    // 更新告警规则
    updateRule(ruleId, updates) {
        const ruleIndex = this.rules.findIndex(r => r.id === ruleId);
        if (ruleIndex === -1) {
            console.error(`规则 ${ruleId} 不存在`);
            return false;
        }

        this.rules[ruleIndex] = { ...this.rules[ruleIndex], ...updates };
        console.log(`告警规则已更新: ${ruleId}`);
        
        return true;
    }

    // 删除告警规则
    deleteRule(ruleId) {
        const initialLength = this.rules.length;
        this.rules = this.rules.filter(r => r.id !== ruleId);
        
        if (this.rules.length < initialLength) {
            console.log(`告警规则已删除: ${ruleId}`);
            return true;
        }
        
        console.error(`规则 ${ruleId} 不存在`);
        return false;
    }

    // 获取所有规则
    getRules() {
        return [...this.rules];
    }

    // 根据ID获取规则
    getRule(ruleId) {
        return this.rules.find(r => r.id === ruleId) || null;
    }

    // 启用规则
    enableRule(ruleId) {
        return this.updateRule(ruleId, { enabled: true });
    }

    // 禁用规则
    disableRule(ruleId) {
        return this.updateRule(ruleId, { enabled: false });
    }

    // 检查规则触发条件
    checkRules(data) {
        if (!this.isRunning) return;

        const dataSource = data.store || data.source;
        if (!dataSource) return;

        this.rules.forEach(rule => {
            // 跳过禁用的规则
            if (!rule.enabled) return;
            
            // 检查数据源是否匹配
            if (rule.dataSource !== dataSource) return;

            try {
                // 使用安全的方式评估条件
                const conditionMet = this.evaluateCondition(rule.condition, { value: data });
                
                if (conditionMet) {
                    this.triggerRule(rule, data);
                } else if (rule.autoResolve && rule.resolveCondition) {
                    // 检查自动解决条件
                    const resolveMet = this.evaluateCondition(rule.resolveCondition, { value: data });
                    if (resolveMet) {
                        this.resolveRelatedAlerts(rule.id, data);
                    }
                }
            } catch (error) {
                console.error(`评估规则 ${rule.id} 时出错:`, error);
            }
        });
    }

    // 评估条件表达式
    evaluateCondition(condition, context) {
        try {
            // 使用Function构造函数而不是eval以提供更好的隔离
            const func = new Function('data', `with(data) { return ${condition}; }`);
            return Boolean(func(context));
        } catch (error) {
            console.error('条件评估错误:', error, '条件:', condition);
            return false;
        }
    }

    // 触发规则
    triggerRule(rule, data) {
        // 检查去抖时间
        const now = Date.now();
        if (rule.debounceTime > 0 && (now - rule._lastFired) < rule.debounceTime) {
            return;
        }

        rule._lastFired = now;
        rule.lastTriggered = now;
        rule.triggerCount++;

        // 创建告警
        const alert = {
            id: `alert_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            ruleId: rule.id,
            ruleName: rule.name,
            severity: rule.severity,
            category: rule.category,
            message: this.generateAlertMessage(rule, data),
            description: rule.description,
            data: { ...data },
            status: 'active',
            createdAt: now,
            updatedAt: now,
            resolvedAt: null,
            acknowledged: false,
            acknowledgedBy: null,
            acknowledgedAt: null
        };

        // 添加告警到列表
        this.alerts.unshift(alert);
        
        // 限制告警数量
        if (this.alerts.length > this.maxAlerts) {
            this.alerts = this.alerts.slice(0, this.maxAlerts);
        }

        // 更新计数器
        this.updateCounters(alert, 'add');

        // 发送通知
        if (rule.notification) {
            this.sendNotification(alert);
        }

        // 触发告警事件
        this.emit('alert:triggered', alert);
        this.emit(`alert:${alert.severity}`, alert);

        return alert;
    }

    // 生成告警消息
    generateAlertMessage(rule, data) {
        const values = this.extractValuesFromData(data);
        let message = rule.name;
        
        if (Object.keys(values).length > 0) {
            const valueString = Object.entries(values)
                .map(([key, value]) => `${key}: ${value}`)
                .join(', ');
            message += ` (${valueString})`;
        }
        
        return message;
    }

    // 从数据中提取值
    extractValuesFromData(data) {
        const values = {};
        
        if (typeof data === 'object' && data !== null) {
            // 提取数字和字符串值
            Object.entries(data).forEach(([key, value]) => {
                if (typeof value === 'number' || typeof value === 'string') {
                    values[key] = value;
                } else if (key === 'value' && typeof value === 'object') {
                    // 处理嵌套的value对象
                    Object.entries(value).forEach(([vkey, vvalue]) => {
                        if (typeof vvalue === 'number' || typeof vvalue === 'string') {
                            values[vkey] = vvalue;
                        }
                    });
                }
            });
        }
        
        return values;
    }

    // 发送通知
    sendNotification(alert) {
        // 如果通知系统可用，使用它发送通知
        if (realTimeSystem.modules.notificationCenter) {
            realTimeSystem.modules.notificationCenter.addNotification({
                title: `告警: ${alert.ruleName}`,
                message: alert.message,
                type: alert.severity,
                category: alert.category,
                data: { alertId: alert.id },
                actions: [
                    { label: '查看详情', action: 'view_alert', data: { alertId: alert.id } },
                    { label: '确认', action: 'acknowledge_alert', data: { alertId: alert.id } }
                ]
            });
        } else {
            // 备用通知方式
            console.warn('通知中心未初始化，无法发送告警通知');
        }
    }

    // 解决相关告警
    resolveRelatedAlerts(ruleId, data) {
        const now = Date.now();
        
        this.alerts.forEach(alert => {
            if (alert.ruleId === ruleId && alert.status === 'active') {
                alert.status = 'resolved';
                alert.updatedAt = now;
                alert.resolvedAt = now;
                
                // 更新计数器
                this.updateCounters(alert, 'resolve');
                
                // 触发告警解决事件
                this.emit('alert:resolved', alert);
            }
        });
    }

    // 更新告警计数器
    updateCounters(alert, action) {
        if (action === 'add') {
            this.alertCounters.total++;
            this.alertCounters.active++;
            this.alertCounters.bySeverity[alert.severity] = 
                (this.alertCounters.bySeverity[alert.severity] || 0) + 1;
        } else if (action === 'resolve') {
            this.alertCounters.active--;
            this.alertCounters.resolved++;
            if (this.alertCounters.bySeverity[alert.severity] > 0) {
                this.alertCounters.bySeverity[alert.severity]--;
            }
        }
    }

    // 获取所有告警
    getAlerts(filter = {}) {
        let alerts = [...this.alerts];
        
        // 应用过滤条件
        if (filter.status) {
            alerts = alerts.filter(a => a.status === filter.status);
        }
        
        if (filter.severity) {
            alerts = alerts.filter(a => a.severity === filter.severity);
        }
        
        if (filter.category) {
            alerts = alerts.filter(a => a.category === filter.category);
        }
        
        if (filter.limit) {
            alerts = alerts.slice(0, filter.limit);
        }
        
        return alerts;
    }

    // 确认告警
    acknowledgeAlert(alertId, userId = 'system') {
        const alert = this.alerts.find(a => a.id === alertId);
        if (!alert) return false;
        
        alert.acknowledged = true;
        alert.acknowledgedBy = userId;
        alert.acknowledgedAt = Date.now();
        alert.updatedAt = Date.now();
        
        this.emit('alert:acknowledged', alert);
        
        return true;
    }

    // 解决告警
    resolveAlert(alertId) {
        const alert = this.alerts.find(a => a.id === alertId);
        if (!alert || alert.status !== 'active') return false;
        
        alert.status = 'resolved';
        alert.resolvedAt = Date.now();
        alert.updatedAt = Date.now();
        
        // 更新计数器
        this.updateCounters(alert, 'resolve');
        
        this.emit('alert:resolved', alert);
        
        return true;
    }

    // 删除告警
    deleteAlert(alertId) {
        const initialLength = this.alerts.length;
        this.alerts = this.alerts.filter(a => a.id !== alertId);
        
        return this.alerts.length < initialLength;
    }

    // 清空所有告警
    clearAllAlerts() {
        this.alerts = [];
        this.alertCounters = {
            total: 0,
            active: 0,
            resolved: 0,
            bySeverity: { critical: 0, high: 0, medium: 0, low: 0 }
        };
        
        this.emit('alerts:cleared');
        
        return true;
    }

    // 获取告警统计
    getStatistics() {
        return { ...this.alertCounters };
    }

    // 注册监听器
    on(event, callback) {
        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }
        this.listeners[event].push(callback);
        
        return () => {
            this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
        };
    }

    // 触发事件
    emit(event, data) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`处理${event}事件时出错:`, error);
                }
            });
        }
    }

    // 停止预警引擎
    stop() {
        this.isRunning = false;
        console.log('智能预警引擎已停止');
    }
}

// 创建并注册预警引擎实例
const alertEngine = new AlertEngine();
realTimeSystem.registerModule('alertEngine', alertEngine);

// 导出预警引擎
window.alertEngine = alertEngine;